package strs

import (
	"fmt"
	"strings"
)

/**
 * 首字母是否大写
 */
func IsFirstUpper(v string) bool {
	if len(v) == 0 {
		return false
	}
	f := v[:1]
	return f == strings.ToUpper(f)
}

/**
 * 按照驼峰法改造字符串
 * 示例:
 *   Hump("hello_world", true) => "HelloWorld"
 *   Hump("hello_world", false) => "helloWorld"
 *   Hump("hello_world", true, "_") => "HelloWorld"
 *   Hump("hello_world", false, "_") => "hello_world"
 *   Hump("hello_world", true, " ") => "HelloWorld"
 */
func Hump(s string, firstUpper bool, sepS ...string) (r string) {
	sep := "_"
	if len(sepS) > 0 {
		sep = sepS[0]
	}
	ss := strings.Split(strings.Trim(strings.Trim(s, " "), sep), sep)
	first := ss[0]
	if first == "" {
		return
	}
	if firstUpper {
		r += strings.ToUpper(first[:1]) + first[1:]
	} else {
		r += strings.ToLower(first[:1]) + first[1:]
	}
	for _, s := range ss[1:] {
		if len(s) == 0 {
			continue
		}
		r += strings.ToUpper(s[:1]) + s[1:]
	}
	return
}

/*
 * 使用map的元素替换字符串中元素
 * @params wrap 不设置表示包裹
 * 示例:
 *   Replace("{{name}} is {{sex}}", map[string]any{ "name": "qingbing", "sex":  "male"}, false) => "{{qingbing}} is {{male}}"
 *   Replace("{{name}} is {{sex}}", map[string]any{ "name": "qingbing", "sex":  "male"}, true) => "qingbing is male"
 */
func Replace(s string, replaces map[string]any, wrap ...bool) string {
	for k, v := range replaces {
		if len(wrap) > 0 && !wrap[0] {
			s = strings.ReplaceAll(s, k, fmt.Sprintf("%v", v))
		} else {
			s = strings.ReplaceAll(s, "{{"+k+"}}", fmt.Sprintf("%v", v))
		}
	}
	return s
}

/**
 * 连接字符串
 * 示例:
 *   Join("_", "hello", "world") => "hello_world"
 *   Join("_", "__hello", "____world__") => "hello_world"
 */
func Join(separator string, strs ...string) string {
	ss := []string{}
	for _, str := range strs {
		if str != "" {
			ss = append(ss, strings.Trim(str, separator))
		}
	}
	return strings.Join(ss, separator)
}
